//
//  ViewController.m
//  我的计步器demo
//
//  Created by hanxiao on 16/2/4.
//  Copyright © 2016年 hanxiao. All rights reserved.
//

#import "ViewController.h"

#import <CoreMotion/CoreMotion.h>

@interface ViewController ()

@property (nonatomic, strong) CMPedometer *stepCounter;
@property (nonatomic, strong) CMMotionActivityManager *activityManager;
@property (nonatomic, strong) NSOperationQueue *operationQueue;

@property (weak, nonatomic) IBOutlet UILabel *stepsLabel;

@property (weak, nonatomic) IBOutlet UILabel *distanceLabel;

@property (weak, nonatomic) IBOutlet UILabel *statusLabel;

@property (weak, nonatomic) IBOutlet UILabel *confidenceLabel;
@end

@implementation ViewController
@synthesize stepsLabel,distanceLabel,statusLabel,confidenceLabel;

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //背景颜色
    self.view.backgroundColor = [UIColor orangeColor];
   
    // Do any additional setup after loading the view, typically from a nib.
    
    
    if (!([CMPedometer isStepCountingAvailable] || [CMMotionActivityManager isActivityAvailable])) {
        
        NSString *msg = @"哎呀，不能运行哦,暂时只能在iPhone5s及以后的设备上玩哦.";
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告!!!"message:msg
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        
        return;
    }
    __weak ViewController *weakSelf = self;
    
    self.operationQueue = [[NSOperationQueue alloc] init];
    
    //更新label
    if ([CMPedometer isStepCountingAvailable])
    {
        
        self.stepCounter = [[CMPedometer alloc] init];
        
    
        NSDate *NowDate=[NSDate date];
        
        NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
        
        [dateformatter setDateFormat:@"HH:mm:ss"];
        
        NSString *locationString=[dateformatter stringFromDate:NowDate];
        
        NSLog(@"locationString:%@",locationString);
        
        NSArray *Datearr = [locationString componentsSeparatedByString:@":"];
        
        NSString *Datestr1 = Datearr[0];
        
        NSString *Datestr2 = Datearr[1];
        
        NSString *Datestr3 = Datearr[2];
        
        double Hour = [Datestr1 doubleValue]*(double)60*60;
        
        double Mint = [Datestr2 doubleValue]*(double)60;
  
        double Secod = [Datestr3 doubleValue];
      
        double total = Hour+Mint+Secod;

    NSDate *startDate = [[NSDate date] dateByAddingTimeInterval:-total];
 
    [self.stepCounter queryPedometerDataFromDate:startDate toDate:NowDate withHandler:^(CMPedometerData *pedometerData, NSError *error)
         {
             dispatch_async(dispatch_get_main_queue(), ^{
                 if (error)
                 {
                     NSLog(@"error: %@", error);
                 }
                 else
                 {
                     NSLog(@"%@",pedometerData);
                     NSString *text = [NSString stringWithFormat:@"步数: %@", pedometerData.numberOfSteps];
                     
                     stepsLabel.text = text;
                     
                     float distance = pedometerData.distance.floatValue/(float)1000;
                     
                     NSString *JuliStr = [NSString stringWithFormat:@"距离: %0.2f公里", distance];
                     
                     distanceLabel.text = JuliStr;
                     
                 }
             });
         }];
        
    }
    
    //运动状态
    if ([CMMotionActivityManager isActivityAvailable]) {
        
        self.activityManager = [[CMMotionActivityManager alloc] init];
        
        [self.activityManager startActivityUpdatesToQueue:self.operationQueue
                                              withHandler:
         ^(CMMotionActivity *activity) {
             
             dispatch_async(dispatch_get_main_queue(), ^{
                 
                 NSString *status = [weakSelf statusForActivity:activity];
                 NSString *confidence = [weakSelf stringFromConfidence:activity.confidence];
                 
                 weakSelf.statusLabel.text = [NSString stringWithFormat:@"状态: %@", status];
                 weakSelf.confidenceLabel.text = [NSString stringWithFormat:@"运动信心值: %@", confidence];
             });
         }];
    }

    // Do any additional setup after loading the view, typically from a nib.
}
- (NSString *)statusForActivity:(CMMotionActivity *)activity
{
    
    NSMutableString *status = @"".mutableCopy;
    
    if (activity.stationary) {
        
        [status appendString:@"not moving"];
    }
    
    if (activity.walking)
    {
        
        if (status.length) [status appendString:@", "];
        
        [status appendString:@"on a walking person"];
    }
    
    if (activity.running) {
        
        if (status.length) [status appendString:@", "];
        
        [status appendString:@"on a running person"];
    }
    
    if (activity.automotive) {
        
        if (status.length) [status appendString:@", "];
        
        [status appendString:@"in a vehicle"];
    }
    
    if (activity.unknown || !status.length) {
        
        [status appendString:@"unknown"];
    }
    
    return status;
}
- (NSString *)stringFromConfidence:(CMMotionActivityConfidence)confidence {
    
    switch (confidence) {
            
        case CMMotionActivityConfidenceLow:
            
            return @"Low";
            
        case CMMotionActivityConfidenceMedium:
            
            return @"Middle";
            
        case CMMotionActivityConfidenceHigh:
            
            return @"High";
            
        default:
            
            return nil;
    }
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
